var s_tn = "02003390_67_hao_pg";
window.offtn_config = true;
var crossOriginHelper = function() {
        var kCallbackFuncKey = "cb",
            requestsIdGenerator = 1,
            taskIds = new Set;

        function buildUrl(url, params, funcName, cbKey) {
            var paramsStr = "";
            for (var key in params) "string" != typeof params[key] && "number" != typeof params[key] && "boolean" !=
            typeof params[key] || (paramsStr.length > 0 && (paramsStr += "&"), paramsStr +=
                `${key}=${encodeURIComponent(params[key])}`);
            paramsStr.length > 0 && (paramsStr += "&"), paramsStr += `${cbKey || "cb"}=${funcName}`;
            var index = url.search(/\?/);
            return index < 0 ? url + "?" + paramsStr : index < url.length - 1 ? url + "&" + paramsStr : url + paramsStr
        }

        function get(url, params, callback, cbKey) {
            var requestId = ++requestsIdGenerator,
                funcName = `crossOriginHelper_${Date.now()}_${requestId}`,
                taskId = `crossOriginHelper_taskId_${Date.now()}_${requestId}`,
                scriptEle = document.createElement("script");
            scriptEle.async = !0, scriptEle.setAttribute("src", buildUrl(url, params, funcName, cbKey)), taskIds.add(
                taskId);
            var internalCallback = data => {
                    taskIds.has(taskId) && (callback(data), taskIds.delete(taskId))
                },
                cleaner = () => {
                    document.body.removeChild(scriptEle), delete window[funcName]
                };
            return window[funcName] = internalCallback, scriptEle.onerror = () => {
                internalCallback(null), cleaner()
            }, scriptEle.onload = () => {
                cleaner()
            }, document.body.appendChild(scriptEle), taskId
        }

        function cancel(taskId) {
            taskIds.delete(taskId)
        }
        return {
            get: get,
            cancel: cancel
        }
    }(),
    searchEngine = {
        action: "https://m.baidu.com/s?ie=utf-8",
        keywordName: "word"
    };

function getSearchURLForKeyword(keyword) {
    var action = searchEngine.action;
    return window.offtn_config && (action = searchEngine.action + `&tn=${s_tn}`), action + "&" + searchEngine
        .keywordName + "=" + encodeURIComponent(keyword)
}

function onSearchSubmitClick(e) {
    var keyword = document.getElementById("search-input").value.trim();
    if (keyword.length < 1) return e.preventDefault(), void e.stopPropagation();
    var url = getSearchURLForKeyword(keyword);
    window.location = url
}

function defaultSuggestionBuilder(data) {
    var keywords = data.s;
    if (keywords.length < 1) return "";
    for (var keywordsHTML = "", i = 0; i < keywords.length; i++) {
        var keyword = keywords[i],
            url;
        keywordsHTML +=
            `<a href="${getSearchURLForKeyword(keyword)}" data-fill="${keyword}">${keyword.replace("&", "&amp;")}</a>`
    }
    return keywordsHTML
}

function suggestionAvailable(data, innerHTMLBuilder) {
    var builder, keywordsHTML = ("function" == typeof innerHTMLBuilder ? innerHTMLBuilder : defaultSuggestionBuilder)(
        data);
    if (keywordsHTML) {
        var searchSuggestion = document.getElementById("search-suggestion");
        searchSuggestion.innerHTML = keywordsHTML, searchSuggestion.hidden = !1, document.getElementById("search-area")
            .classList.add("line-controls-focus"), searchSuggestion.style.width = document.getElementById("search-area")
            .offsetWidth - 2 + "px"
    }
}
var lastRequestKeyword = "";

function onSearchInput() {
    var keyword = document.getElementById("search-input").value.trim();
    if (keyword) {
        if (keyword != lastRequestKeyword || document.getElementById("search-suggestion").hidden) {
            var url = "https://suggestion.baidu.com/su?ie=utf-8&action=json";
            requestTaskId = crossOriginHelper.get(url, {
                wd: keyword
            }, (function(data) {
                suggestionAvailable(data)
            })), lastRequestKeyword = keyword
        }
    } else requestHotSuggestion()
}
var requestTaskId = null,
    cachedHostSugs = null,
    e = document.createElement("script");
e.type = "text/javascript", e.src = "https://wap.sogou.com/data/hotwords/sogou_top10_hotword.js?_t=" + Date.now(),
    document.body.appendChild(e);
var hotsearch_list = [];

function requestHotSuggestion() {
    suggestionAvailable(hotsearch_list, (function(data) {
        for (var hotSugHTML = "", i = 0; i < hotsearch_list.length; i++) {
            let link;
            hotSugHTML +=
                `<a href="${`https://m.baidu.com/s?ie=utf-8${!0 === window.offtn_config ? "&tn=" + s_tn : ""}&wd=${hotsearch_list[i].word}`}" data-fill="${hotsearch_list[i].word}"><em>${i + 1}</em>${hotsearch_list[i].word}</a>`
        }
        return hotSugHTML
    })), cachedHostSugs = hotsearch_list
}

function cancelRequestHotSuggetionOrKeyword() {
    requestTaskId && (crossOriginHelper.cancel(requestTaskId), requestTaskId = null)
}

function onSuggestionNav(isDown) {
    var aEles = document.getElementById("search-suggestion").children;
    if (!(aEles.length < 1)) {
        for (var index = isDown ? -1 : 0, i = 0; i < aEles.length; i++) {
            var aEle = aEles[i];
            if (aEle.classList.contains("on")) {
                aEle.classList.toggle("on", !1), index = i;
                break
            }
        }
        aEles[index = ((index += isDown ? 1 : -1) + aEles.length) % aEles.length].classList.toggle("on", !0), document
            .getElementById("search-input").value = aEles[index].dataset.fill
    }
}

function onSearchInputKeydown(event) {
    switch (event.key) {
        case "ArrowUp":
            document.getElementById("search-suggestion").hidden || onSuggestionNav(!1), event.stopPropagation(), event
                .preventDefault();
            break;
        case "ArrowDown":
            document.getElementById("search-suggestion").hidden ? onSearchInput() : onSuggestionNav(!0), event
                .stopPropagation(), event.preventDefault()
    }
}

function onMousedownForSearchInput(e) {
    if (0 == e.button) {
        var searchSuggestion = document.getElementById("search-suggestion");
        "search-input" == e.target.id || e.target == searchSuggestion || searchSuggestion.contains(e.target) || (
            cancelRequestHotSuggetionOrKeyword(), document.getElementById("search-suggestion").hidden = !0, document
                .getElementById("search-area").classList.remove("line-controls-focus"))
    }
}

function initSearch() {
    var searchForm;
    document.getElementById("search-form").onsubmit = () => !1;
    var searchInput = document.getElementById("search-input"),
        submit;
    searchInput.autocomplete = "off", searchInput.addEventListener("input", onSearchInput), searchInput
        .addEventListener("keydown", onSearchInputKeydown), searchInput.addEventListener("mousedown", onSearchInput),
        document.addEventListener("mousedown", onMousedownForSearchInput), window.addEventListener("blur", (function() {
        cancelRequestHotSuggetionOrKeyword(), document.getElementById("search-suggestion").hidden = !0,
            document.getElementById("search-area").classList.remove("line-controls-focus")
    })), document.getElementById("submit").onclick = onSearchSubmitClick;
    var searchSuggestion = document.getElementById("search-suggestion");
    searchSuggestion.hidden = !0, document.getElementById("search-area").classList.remove("line-controls-focus"),
        searchSuggestion.addEventListener("click", (function(e) {
            document.getElementById("search-input").value.trim() && e.srcElement.tagName
        }))
}

function search_model_click() {
    let info_switch;
    "1" === (localStorage.getItem("iv_switch") || "1") && ($(".s_setting_item").removeClass("current"), $(
        '.s_setting_item[data-val="0"]').addClass("current"), localStorage.setItem("iv_switch", "0"), location
        .reload());
}

function info_model_click() {
    let info_switch;
    "1" !== (localStorage.getItem("iv_switch") || "1") && ($(".s_setting_item").removeClass("current"), $(
        '.s_setting_item[data-val="1"]').addClass("current"), localStorage.setItem("iv_switch", "1"), location
        .reload());
}

function init_menu() {
    let s_layer = $(".s_layer");
    document.querySelector(".icon-setting").onclick = function() {
        this.style.color = "#666666", s_layer.slideDown("slow")
    }, document.querySelector(".s_layer").onclick = function(e) {
        e.target === this && s_layer.slideUp("slow", () => {
            document.querySelector(".icon-setting").removeAttribute("style")
        })
    };
    let info_switch = localStorage.getItem("iv_switch") || "1";
    info_switch = "1" === info_switch ? "1" : "0", $(`.s_setting_item[data-val="${info_switch}"]`).addClass("current")
}

function drag_nav() {
    let ct = document.querySelector(".s-nav-area").firstElementChild;
    new Sortable(ct, {
        animation: 150,
        onEnd: function(evt) {
            let data = [];
            $(ct).children().each((i, _t) => {
                let item = _t.firstElementChild,
                    p = "" !== item.getAttribute("lang") ? item.getAttribute("lang") : item
                        .getAttribute("href");
                data.push({
                    l: p,
                    t: item.getAttribute("title"),
                    i: item.firstElementChild.firstElementChild.getAttribute("src")
                })
            }), localStorage.setItem("nav_sort", JSON.stringify(data))
        }
    })
}

function load_nav_item() {
    let data = localStorage.getItem("nav_sort");
    data ? insert_nav_tpl(JSON.parse(data)) : fetch_nav()
}

function insert_nav_tpl(nav_data) {
    let ct = document.getElementById("news-info"),
        html = "";
    nav_data.forEach((item, index) => {
        let t = item.b ? item.b : "";
        html +=
            `\n            <div class="nav-item">\n                <a href="${item.l}" lang="${t}" title="${item.t}" class="nav-block c-color-gray" target="_blank" data-click="LOG_LINK" data-pos="0">\n                <span class="c-img c-img-radius-large nav-img"><img height="64" width="64" src="${item.i}"></span>\n                <span class="nav-txt">${item.t}</span><span class="nav-img-mask"></span></a></div>\n            `
    }), ct.innerHTML = html, drag_nav()
}

function fetch_nav() {
    let url = "./js/nav_all.json";
    $.get(url, null, data => {
        insert_nav_tpl(data)
    })
}
window.hotwords = function(data) {
    function fun(data) {
        return function(a, b) {
            return a[data] - b[data]
        }
    }
    data.sort(fun("weight")), $(".s-news-rank-content").html(""), hotsearch_list = data, data.forEach((item, i) => {
        $(".s-news-rank-content").append(
            `<li class="news-meta-item clearfix" data-index="0"><a class="title-content c-link c-font-medium" href="https://m.baidu.com/s?ie=utf-8${!0 === window.offtn_config ? "&tn=" + s_tn : ""}&wd=${item.word}" target="_blank">\n        <span class="title-content-index c-color-gray2 top-${i}">${i + 1}</span>\n        <span class="title-content-title">${item.word}</span> </a> </li>`
        )
    })
}, initSearch(), $((function() {
    let info_switch;
    load_nav_item(), init_menu(), "0" !== (localStorage.getItem("iv_switch") || "1") && (document
        .querySelector(".s_search_wrap").style.display = "block", document.querySelector(".s_wrap")
        .removeAttribute("style"))
}));
